//
//  SQPageCollectionLayout.swift
//  SQPageView
//
//  Created by ToothBond on 2017/4/27.
//  Copyright © 2017年 rensq. All rights reserved.
//

import UIKit

class SQPageCollectionLayout: UICollectionViewLayout {
    
    var sectionInset = UIEdgeInsets.zero
    var itemMargin : CGFloat = 0
    var lineMargin : CGFloat = 0
    var numberOfCol : Int = 4
    var numberOfRow : Int = 2
    fileprivate var totalWidth : CGFloat = 0
    
    fileprivate lazy var attributes = [UICollectionViewLayoutAttributes]()

}

extension SQPageCollectionLayout {
    override func prepare() {
        super.prepare()
        //获取collectionView中有多少组
        guard let collectionView = collectionView else {return}
        let sections = collectionView.numberOfSections
        
        let itemW = (collectionView.bounds.width - sectionInset.left - sectionInset.right - (CGFloat(numberOfCol)-1)*itemMargin)/CGFloat(numberOfCol)
        let itemH = (collectionView.bounds.height - sectionInset.top - sectionInset.bottom - CGFloat(numberOfRow-1)*lineMargin)/CGFloat(numberOfRow)
        
        var previousNumOfPage = 0   //
        for section in 0..<sections {
            //获取每组中的items
            let items = collectionView.numberOfItems(inSection: section)
            
            for itemIdx in 0..<items {
                let attribute = UICollectionViewLayoutAttributes(forCellWith: IndexPath(item: itemIdx, section: section))
                let currentPageInSection = itemIdx/(numberOfRow * numberOfCol)
                let currentIndexInPage = itemIdx % (numberOfRow * numberOfCol)
                
                //之前每组的宽度累计 + 当前item所在的页的宽度 + item在当前页的x
                let x = CGFloat(previousNumOfPage + currentPageInSection) * collectionView.bounds.width + sectionInset.left + (itemW + itemMargin) * CGFloat(currentIndexInPage % numberOfCol)
                let y = sectionInset.top + (itemH + lineMargin) * CGFloat(currentIndexInPage / numberOfCol)

                attribute.frame = CGRect(x: x, y: y, width: itemW, height: itemH)
                attributes.append(attribute)
            }
            //累加每组的页数
            previousNumOfPage += (items-1)/(numberOfCol * numberOfRow) + 1
        }
        
        totalWidth = CGFloat(previousNumOfPage) * collectionView.bounds.width
    }
    
    override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
        
        return attributes
    }
    
    override var collectionViewContentSize: CGSize {
        return CGSize(width: totalWidth, height: 0)
    }
}
